package com.lean.android.ad.core.interstitial

import android.app.Activity
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd.FullScreenVideoAdInteractionListener
import com.lean.android.ad.core.AdRenderCallback
import com.lean.android.ad.core.AdRenderer
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt

@RestrictTo(RestrictTo.Scope.LIBRARY)
class InterstitialAdRenderer(private val activity: Activity) :
    AdRenderer<InterstitialAd, AdRenderCallback> {

    override fun render(ad: InterstitialAd, renderCallback: AdRenderCallback) {
        val nativeAd = ad.ad
        if (nativeAd.mediationManager.isReady) {
            nativeAd.setFullScreenVideoAdInteractionListener(object :
                FullScreenVideoAdInteractionListener {
                override fun onAdShow() {
                    nativeAd.mediationManager?.showEcpm?.also { cpmInfo ->
                        val cpm = cpmInfo.ecpm.toCpmInt()
                        val adPosition =
                            if (ad.fullAd) ReportHelper.AdPositionType.Full else ReportHelper.AdPositionType.Interstitial

                        ReportHelper.reportAdEvent(
                            requestId = ad.requestId,
                            eventType = ReportHelper.AdEventType.AdShowed,
                            platformId = cpmInfo.sdkName.orEmpty(),
                            adPosition = adPosition,
                            cpm = cpm
                        )
                    }
                    renderCallback.onAdShow(ad, 0, 0)
                }

                override fun onAdVideoBarClick() {

                }

                override fun onAdClose() {
                    renderCallback.onAdClosed(ad)
                }

                override fun onVideoComplete() {

                }

                override fun onSkippedVideo() {

                }
            })
            nativeAd.showFullScreenVideoAd(activity)
        } else {
            renderCallback.onAdClosed(ad)
        }
    }
}